<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. Mybatis官网下载地址解压之后的内容：">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaEE-Mybatis使用">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Mybatis使用/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. Mybatis官网下载地址解压之后的内容：">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-c32033bb371722ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-fe1088c3d8aebc5d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-031e07e9eed24120.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-6217d4c2c60a424f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-1ea7fe6964dcfd17.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-a749eb46e7852d81.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-50f834225a5e3ce1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-48e075c56af47126.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-42acf9848b151b70.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-54fa548b551c61ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-060b650d0781ffbf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ab72ad9c143dea9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-e3db597f95883ed3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-bcc8a741dfb08923.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-13966f666203e136.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-29ac93c627360375.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8b871b1815247e17.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:51:24.850Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaEE-Mybatis使用">
<meta name="twitter:description" content="####1. Mybatis官网下载地址解压之后的内容：">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-c32033bb371722ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Mybatis使用/"/>





  <title>JavaEE-Mybatis使用 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/JakartaEE-Framework/JavaEE-Mybatis使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaEE-Mybatis使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. <a href="http://www.mybatis.org/mybatis-3/zh/" target="_blank" rel="noopener">Mybatis官网</a><br><a href="https://github.com/mybatis/mybatis-3" target="_blank" rel="noopener">下载地址</a><br>解压之后的内容：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-c32033bb371722ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"><br><a id="more"></a></p>
<p>Mybatis框架结构：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-fe1088c3d8aebc5d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"><br>简要概述：</p>
<ul>
<li>SqlMapConfig.xml，此文件作为mybatis的全局配置文件，配置了mybatis的运行环境等信息。mapper.xml文件即sql映射文件，文件中配置了操作数据库的sql语句，此文件需要在SqlMapConfig.xml中加载。</li>
<li>通过mybatis环境等配置信息构造SqlSessionFactory(即会话工厂)。</li>
<li>由会话工厂创建sqlSession即会话，操作数据库需要通过sqlSession进行。</li>
<li>mybatis底层自定义了Executor执行器接口操作数据库，Executor接口有两个实现，一个是基本执行器、一个是缓存执行器。</li>
<li>MappedStatement也是mybatis一个底层封装对象，它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个MappedStatement对象，sql的id即是MappedStatement的id。</li>
<li>MappedStatement对sql执行输入参数进行定义，包括HashMap、基本类型、pojo，Executor通过MappedStatement在执行sql前将输入的java对象映射至sql中，输入参数映射就是JDBC编程中对preparedStatement设置参数。</li>
<li>MappedStatement对sql执行输出结果进行定义，包括HashMap、基本类型、pojo，Executor通过MappedStatement在执行sql后将输出结果映射至java对象中，输出结果映射过程相当于JDBC编程中对结果的解析处理过程。</li>
</ul>
<p>####2. 导入数据库表<br>1). 使用Navicat工具，在root上右键选择新建数据库<br><img src="https://upload-images.jianshu.io/upload_images/3110861-031e07e9eed24120.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"><br>2). 新建数据库-&gt;确定<br><img src="https://upload-images.jianshu.io/upload_images/3110861-6217d4c2c60a424f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"><br>3). 打开数据库mybatis-&gt;在mybatis/表处单击右键选择运行SQL文件…<br><img src="https://upload-images.jianshu.io/upload_images/3110861-1ea7fe6964dcfd17.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"><br>4). 选择桌面的sql文件-&gt;点击开始<br><img src="https://upload-images.jianshu.io/upload_images/3110861-a749eb46e7852d81.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"><br><strong>mybatis.sql文件内容</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">SET FOREIGN_KEY_CHECKS=0;</span><br><span class="line"></span><br><span class="line">-- ----------------------------</span><br><span class="line">-- Table structure for `orders`</span><br><span class="line">-- ----------------------------</span><br><span class="line">DROP TABLE IF EXISTS `orders`;</span><br><span class="line">CREATE TABLE `orders` (</span><br><span class="line">  `id` int(11) NOT NULL AUTO_INCREMENT,</span><br><span class="line">  `user_id` int(11) NOT NULL COMMENT &apos;下单用户id&apos;,</span><br><span class="line">  `number` varchar(32) NOT NULL COMMENT &apos;订单号&apos;,</span><br><span class="line">  `createtime` datetime NOT NULL COMMENT &apos;创建订单时间&apos;,</span><br><span class="line">  `note` varchar(100) DEFAULT NULL COMMENT &apos;备注&apos;,</span><br><span class="line">  PRIMARY KEY (`id`),</span><br><span class="line">  KEY `FK_orders_1` (`user_id`),</span><br><span class="line">  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION</span><br><span class="line">) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;</span><br><span class="line"></span><br><span class="line">-- ----------------------------</span><br><span class="line">-- Records of orders</span><br><span class="line">-- ----------------------------</span><br><span class="line">INSERT INTO `orders` VALUES (&apos;3&apos;, &apos;1&apos;, &apos;1000010&apos;, &apos;2015-02-04 13:22:35&apos;, null);</span><br><span class="line">INSERT INTO `orders` VALUES (&apos;4&apos;, &apos;1&apos;, &apos;1000011&apos;, &apos;2015-02-03 13:22:41&apos;, null);</span><br><span class="line">INSERT INTO `orders` VALUES (&apos;5&apos;, &apos;10&apos;, &apos;1000012&apos;, &apos;2015-02-12 16:13:23&apos;, null);</span><br><span class="line"></span><br><span class="line">-- ----------------------------</span><br><span class="line">-- Table structure for `user`</span><br><span class="line">-- ----------------------------</span><br><span class="line">DROP TABLE IF EXISTS `user`;</span><br><span class="line">CREATE TABLE `user` (</span><br><span class="line">  `id` int(11) NOT NULL AUTO_INCREMENT,</span><br><span class="line">  `username` varchar(32) NOT NULL COMMENT &apos;用户名称&apos;,</span><br><span class="line">  `birthday` date DEFAULT NULL COMMENT &apos;生日&apos;,</span><br><span class="line">  `sex` char(1) DEFAULT NULL COMMENT &apos;性别&apos;,</span><br><span class="line">  `address` varchar(256) DEFAULT NULL COMMENT &apos;地址&apos;,</span><br><span class="line">  PRIMARY KEY (`id`)</span><br><span class="line">) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;</span><br><span class="line"></span><br><span class="line">-- ----------------------------</span><br><span class="line">-- Records of user</span><br><span class="line">-- ----------------------------</span><br><span class="line">INSERT INTO `user` VALUES (&apos;1&apos;, &apos;王五&apos;, null, &apos;2&apos;, null);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;10&apos;, &apos;张三&apos;, &apos;2014-07-10&apos;, &apos;1&apos;, &apos;北京市&apos;);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;16&apos;, &apos;张小明&apos;, null, &apos;1&apos;, &apos;河南郑州&apos;);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;22&apos;, &apos;陈小明&apos;, null, &apos;1&apos;, &apos;河南郑州&apos;);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;24&apos;, &apos;张三丰&apos;, null, &apos;1&apos;, &apos;河南郑州&apos;);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;25&apos;, &apos;陈小明&apos;, null, &apos;1&apos;, &apos;河南郑州&apos;);</span><br><span class="line">INSERT INTO `user` VALUES (&apos;26&apos;, &apos;王五&apos;, null, null, null);</span><br></pre></td></tr></table></figure></p>
<p>5). 导入成功后，刷新表，数据如下：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-50f834225a5e3ce1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>####3. 测试<br>1). 创建新的Java工程，并导入Mybatis使用的java包，注意要导入对应的数据库驱动包(这里导入的是mysql-connector-java-5.1.42-bin.jar)<br><img src="https://upload-images.jianshu.io/upload_images/3110861-48e075c56af47126.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>2). 在工程目录下创建一个源码包config，并在config包下创建sqlmap包、log4j.properties和SqlMapConfig.xml文件。<br><img src="https://upload-images.jianshu.io/upload_images/3110861-42acf9848b151b70.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p><strong>log4j.properties文件内容</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># Global logging configuration</span><br><span class="line">log4j.rootLogger=DEBUG, stdout</span><br><span class="line"># Console output...</span><br><span class="line">log4j.appender.stdout=org.apache.log4j.ConsoleAppender</span><br><span class="line">log4j.appender.stdout.layout=org.apache.log4j.PatternLayout</span><br><span class="line">log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n</span><br></pre></td></tr></table></figure></p>
<p><strong>SqlMapConfig.xml文件内容</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;</span><br><span class="line">&lt;configuration&gt;</span><br><span class="line">    &lt;!-- 和spring整合后environments配置将废除 --&gt;</span><br><span class="line">    &lt;environments default=&quot;development&quot;&gt;</span><br><span class="line">        &lt;environment id=&quot;development&quot;&gt;</span><br><span class="line">            &lt;!-- 使用jdbc事务管理 --&gt;</span><br><span class="line">            &lt;transactionManager type=&quot;JDBC&quot; /&gt;</span><br><span class="line">            &lt;!-- 数据库连接池 --&gt;</span><br><span class="line">            &lt;dataSource type=&quot;POOLED&quot;&gt;</span><br><span class="line">                &lt;property name=&quot;driver&quot; value=&quot;com.mysql.jdbc.Driver&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;username&quot; value=&quot;root&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;password&quot; value=&quot;root&quot; /&gt;</span><br><span class="line">            &lt;/dataSource&gt;</span><br><span class="line">        &lt;/environment&gt;</span><br><span class="line">    &lt;/environments&gt;</span><br><span class="line">&lt;/configuration&gt;</span><br></pre></td></tr></table></figure></p>
<p>SqlMapConfig.xml是mybatis的核心配置文件，以上文件的配置内容为数据源、事务管理。<br><strong>注意：等后面mybatis和Spring两个框架整合之后，environments的配置将被废除.</strong><br>3). 创建一个po类–User<br>po类作为mybatis进行sql映射使用，po类通常与数据库表对应，User.java文件的内容如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">public class User &#123;</span><br><span class="line">	// id</span><br><span class="line">	private int id;</span><br><span class="line">	// 用户名</span><br><span class="line">	private String username;</span><br><span class="line">	// 性别</span><br><span class="line">	private String sex;</span><br><span class="line">	// 用户名</span><br><span class="line">	private Date birthday;</span><br><span class="line">	// 地址</span><br><span class="line">	private String address;</span><br><span class="line">	public int getId() &#123;</span><br><span class="line">		return id;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setId(int id) &#123;</span><br><span class="line">		this.id = id;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getUsername() &#123;</span><br><span class="line">		return username;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setUsername(String username) &#123;</span><br><span class="line">		this.username = username;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getSex() &#123;</span><br><span class="line">		return sex;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setSex(String sex) &#123;</span><br><span class="line">		this.sex = sex;</span><br><span class="line">	&#125;</span><br><span class="line">	public Date getBirthday() &#123;</span><br><span class="line">		return birthday;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setBirthday(Date birthday) &#123;</span><br><span class="line">		this.birthday = birthday;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getAddress() &#123;</span><br><span class="line">		return address;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setAddress(String address) &#123;</span><br><span class="line">		this.address = address;</span><br><span class="line">	&#125;</span><br><span class="line">	@Override</span><br><span class="line">	public String toString() &#123;</span><br><span class="line">		return &quot;User [id=&quot; + id + &quot;, username=&quot; + username + &quot;, sex=&quot; + sex + &quot;, birthday=&quot; + birthday + &quot;, address=&quot;</span><br><span class="line">				+ address + &quot;]&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>4). 在classpath下的sqlmap目录下创建sql映射文件user.xml<br><strong>user.xml内容如下：</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line"></span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>namespace：即命名空间，其用于隔离sql语句(即不同sql映射文件中的两个相同id的sql语句如何来区分)</li>
</ul>
<p>5). 加载映射文件<br>mybatis框架需要加载映射文件，将user.xml添加在SqlMapConfig.xml中.<br>在SqlMapConfig.xml配置文件中添加配置信息：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;</span><br><span class="line">&lt;configuration&gt;</span><br><span class="line">    &lt;!-- 和spring整合后environments配置将废除 --&gt;</span><br><span class="line">    &lt;environments default=&quot;development&quot;&gt;</span><br><span class="line">        &lt;environment id=&quot;development&quot;&gt;</span><br><span class="line">            &lt;!-- 使用jdbc事务管理 --&gt;</span><br><span class="line">            &lt;transactionManager type=&quot;JDBC&quot; /&gt;</span><br><span class="line">            &lt;!-- 数据库连接池 --&gt;</span><br><span class="line">            &lt;dataSource type=&quot;POOLED&quot;&gt;</span><br><span class="line">                &lt;property name=&quot;driver&quot; value=&quot;com.mysql.jdbc.Driver&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;username&quot; value=&quot;root&quot; /&gt;</span><br><span class="line">                &lt;property name=&quot;password&quot; value=&quot;root&quot; /&gt;</span><br><span class="line">            &lt;/dataSource&gt;</span><br><span class="line">        &lt;/environment&gt;</span><br><span class="line">    &lt;/environments&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;!-- 添加的内容 --&gt;</span><br><span class="line">    &lt;mappers&gt;</span><br><span class="line">    	&lt;!-- resource是基于classpath来查找的 --&gt;</span><br><span class="line">    	&lt;mapper resource=&quot;sqlmap/user.xml&quot;/&gt;</span><br><span class="line">    &lt;/mappers&gt;</span><br><span class="line">&lt;/configuration&gt;</span><br></pre></td></tr></table></figure></p>
<p>6). 入门程序测试——根据id查询用户信息<br>I. user.xml映射文件中添加如下配置：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line">	&lt;!-- 根据id获取用户信息,</span><br><span class="line">		parameterType: 查询参数的数据类型，即定义输入到sql中的映射类型</span><br><span class="line">		resultType: 查询结果的数据类型，如果是pojo则该给出全路径</span><br><span class="line">		#&#123;id&#125;表示使用PreparedStatement设置占位符号并将输入变量id传到sql中,#&#123;&#125;作用就是占位符,相当于JDBC中的? </span><br><span class="line">	 --&gt;</span><br><span class="line">	&lt;select id=&quot;getUserById&quot; parameterType=&quot;int&quot; resultType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		select * from user where id = #&#123;id&#125;;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 编写MybatisTest类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void	testGetUserById() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		SqlSessionFactory factory = builder.build(inputStream);</span><br><span class="line">		// 4. 创建SqlSession对象</span><br><span class="line">		SqlSession sqlSession = factory.openSession();</span><br><span class="line">		// 5. 使用SqlSession对象执行查询，得到User对象</span><br><span class="line">		// 第一个参数： 执行查询的StatementId，即配置文件user.xml中的id， 第二参数传入id对应的值</span><br><span class="line">		User user = sqlSession.selectOne(&quot;getUserById&quot;, 10);</span><br><span class="line">		// 6. 打印结果</span><br><span class="line">		System.out.println(user);</span><br><span class="line">		// 7. 释放资源</span><br><span class="line">		sqlSession.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 执行测试代码, 打印结果:<br><img src="https://upload-images.jianshu.io/upload_images/3110861-54fa548b551c61ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<p>IV. 优化代码<br>一般来讲工厂对象一般在实际开发是单例的，并不需要频繁地创建<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void	testGetUserById() &#123;</span><br><span class="line">		// 4. 创建SqlSession对象</span><br><span class="line">		SqlSession sqlSession = factory.openSession();</span><br><span class="line">		// 5. 使用SqlSession对象执行查询，得到User对象</span><br><span class="line">		// 第一个参数： 执行查询的StatementId，即配置文件user.xml中的id， 第二参数传入id对应的值</span><br><span class="line">		User user = sqlSession.selectOne(&quot;getUserById&quot;, 10);</span><br><span class="line">		// 6. 打印结果</span><br><span class="line">		System.out.println(user);</span><br><span class="line">		// 7. 释放资源</span><br><span class="line">		sqlSession.close();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>7). 根据用户名称模糊查询用户信息列表<br>I. user.xml文件添加<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;	</span><br><span class="line">	&lt;!-- 如果查询结果返回的是List集合，那么resultType只需要设置为List集合中的一个元素的数据类型 --&gt;</span><br><span class="line">	&lt;select id=&quot;getUserByName&quot; parameterType=&quot;string&quot; resultType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		select * from user where username like #&#123;username&#125;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 编写测试方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testGetUserByName() &#123;</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		List&lt;User&gt; list = session.selectList(&quot;getUserByName&quot;, &quot;%张%&quot;);</span><br><span class="line">		for (User user : list) &#123;</span><br><span class="line">			System.out.println(user.toString());</span><br><span class="line">		&#125;</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 执行测试方法，打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-060b650d0781ffbf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"></p>
<p>IV. 另一个中不建议使用的占位符方式<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line">		&lt;!-- 如果查询结果返回的是List集合，那么resultType只需要设置为List集合中的一个元素的数据类型 --&gt;</span><br><span class="line">	&lt;select id=&quot;getUserByName1&quot; parameterType=&quot;string&quot; resultType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		select * from user where username like &apos;%$&#123;value&#125;%&apos;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>测试代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testGetUserByName1() &#123;</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		List&lt;User&gt; list = session.selectList(&quot;getUserByName1&quot;, &quot;张&quot;);</span><br><span class="line">		for (User user : list) &#123;</span><br><span class="line">			System.out.println(user.toString());</span><br><span class="line">		&#125;</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-ab72ad9c143dea9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图11.png"><br><strong>不推荐使用：原因容易引起SQL注入。</strong></p>
<p>####总结</p>
<p>#####—{}和${}<br>1). <code>#{}</code>：表示一个占位符号，可以很好地去避免sql注入。其原理是将占位符位置的整个参数和sql语句两部分提交给数据库，数据库去执行sql语句，去表中匹配所有的记录是否和整个参数是否一致。<br><code>#{}</code>要获取输入参数的值：</p>
<ul>
<li>如果输入参数是简单数据类型，则<code>#{}</code>中可以写value或其它名称。</li>
<li>如果输入参数是pojo对象类型，则<code>#{}</code>可通过OGNL方式去获取，表达式就是<code>属性.属性.属性....</code>方式。</li>
</ul>
<p>2). <code>${}</code>表示一个sql拼接符号，其原理是在向数据库发出sql之前去拼接好sql再提交给数据库执行。<br><code>${}</code>要获取输入参数的值：</p>
<ul>
<li>如果输入参数是简单数据类型，则<code>${}</code>中只能写value。</li>
<li>如果输入参数是pojo对象类型，则<code>${}</code>可通过OGNL方式去获取，表达式就是<code>属性.属性.属性....</code>方式。</li>
</ul>
<p>一般情况下建议使用<code>#{}</code>，特殊情况下必须要用<code>${}</code>，比如：</p>
<p>1&gt;.  动态拼接sql中动态组成排序字段，要通过<code>${}</code>将排序字段传入sql中。<br>2&gt;.  动态拼接sql中动态组成表名，要通过<code>${}</code>将表名传入sql中。</p>
<p>#####—parameterType和resultType</p>
<ul>
<li>parameterType：指定输入参数类型，mybatis通过ognl从输入对象中获取参数值拼接在sql中。 </li>
<li>resultType：指定输出结果类型，mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。</li>
</ul>
<p>#####—selectOne()和selectList()方法</p>
<ul>
<li>selectOne查询一条记录，如果使用selectOne查询多条记录则抛出异常.</li>
<li>selectList可以查询一条或多条记录。</li>
</ul>
<p>####4. 其他操作<br>1). 插入数据<br>I. user.xml添加配置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line">	&lt;!-- 插入数据 --&gt;</span><br><span class="line">	&lt;insert id=&quot;addUser&quot; parameterType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		insert into user(username,birthday,sex,address) values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">	&lt;/insert&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p><strong>如果输入参数是pojo，那么#{}中的名称就是pojo类中的属性（用到了对象图导航的思想）</strong><br>II. 编写测试代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testAddUser() &#123;</span><br><span class="line">		// 创建Session对象</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		// 创建对象</span><br><span class="line">		User user = new User();</span><br><span class="line">		user.setUsername(&quot;mazaiting&quot;);</span><br><span class="line">		user.setBirthday(new Date());</span><br><span class="line">		user.setSex(&quot;男&quot;);</span><br><span class="line">		user.setAddress(&quot;科学院&quot;);</span><br><span class="line">		</span><br><span class="line">		// 插入数据</span><br><span class="line">		session.insert(&quot;addUser&quot;, user);</span><br><span class="line">		// 关闭Session</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 执行测试代码，打印结果:<br>可以看出虽然执行了sql语句，但是事务并没有提交，而是回滚了。<br><img src="https://upload-images.jianshu.io/upload_images/3110861-e3db597f95883ed3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图12.png"></p>
<p>IV. 因此，应将测试代码修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	@Test</span><br><span class="line">	public void testAddUser() &#123;</span><br><span class="line">		// 创建Session对象</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		// 创建对象</span><br><span class="line">		User user = new User();</span><br><span class="line">		user.setUsername(&quot;mazaiting&quot;);</span><br><span class="line">		user.setBirthday(new Date());</span><br><span class="line">		user.setSex(&quot;男&quot;);</span><br><span class="line">		user.setAddress(&quot;科学院&quot;);</span><br><span class="line">		</span><br><span class="line">		// 插入数据</span><br><span class="line">		session.insert(&quot;addUser&quot;, user);</span><br><span class="line">		// 提交事务</span><br><span class="line">		session.commit();</span><br><span class="line">		// 关闭Session</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>V. 执行单元测试，打印结果:<br><img src="https://upload-images.jianshu.io/upload_images/3110861-bcc8a741dfb08923.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图13.png"></p>
<p>2). 自增主键返回</p>
<ul>
<li>LAST_INSERT_ID()：返回auto_increment自增列新记录id值。该函数是在当前事务下取到你最后生成的id值，而我们应知道查询操作是没有开启事务的，增删改操作是需要开启事务的。</li>
</ul>
<p>I. 在user.xml中添加配置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;	</span><br><span class="line">	&lt;!-- 插入数据,返回主键 --&gt;</span><br><span class="line">	&lt;insert id=&quot;addUser&quot; parameterType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		&lt;selectKey keyProperty=&quot;id&quot; resultType=&quot;int&quot; order=&quot;AFTER&quot;&gt;</span><br><span class="line">			select LAST_INSERT_ID()</span><br><span class="line">		&lt;/selectKey&gt;</span><br><span class="line">		insert into user(username,birthday,sex,address) values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">	&lt;/insert&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>keyProperty：返回的主键存储在pojo中的哪个属性(即其对应pojo的主键属性)。获取主键，实际上是将主键取出来之后封装到了pojo的主键属性当中。</li>
<li>resultType：返回的主键是什么类型(即其对应pojo的主键的数据类型)。</li>
<li>order：selectKey的执行顺序，是相对于insert语句来说的，由于mysql的自增原理，执行完insert语句之后才将主键生成，所以这里selectKey的执行顺序为AFTER。</li>
</ul>
<p>II. 添加测试代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testAddUser1() &#123;</span><br><span class="line">		// 创建Session对象</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		// 创建对象</span><br><span class="line">		User user = new User();</span><br><span class="line">		user.setUsername(&quot;mazaiting&quot;);</span><br><span class="line">		user.setBirthday(new Date());</span><br><span class="line">		user.setSex(&quot;男&quot;);</span><br><span class="line">		user.setAddress(&quot;科学院&quot;);</span><br><span class="line">		</span><br><span class="line">		// 插入数据</span><br><span class="line">		session.insert(&quot;addUser1&quot;, user);</span><br><span class="line">		System.out.println(&quot;插入的id：&quot; + user.getId());</span><br><span class="line">		// 提交事务</span><br><span class="line">		session.commit();</span><br><span class="line">		// 关闭Session</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 执行测试代码，打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-13966f666203e136.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图14.png"></p>
<p>3). 删除用户<br>I. user.xml中添加删除语句<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line">	&lt;!-- 删除数据 --&gt;</span><br><span class="line">	&lt;delete id=&quot;deleteUser&quot; parameterType=&quot;int&quot;&gt;</span><br><span class="line">		delete from user where id = #&#123;id&#125;</span><br><span class="line">	&lt;/delete&gt;</span><br><span class="line">	</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 测试代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testDeleteUser() &#123;</span><br><span class="line">		// 创建会话</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		// 删除数据</span><br><span class="line">		session.delete(&quot;deleteUser&quot;, 29);</span><br><span class="line">		// 提交事务</span><br><span class="line">		session.commit();</span><br><span class="line">		// 关闭会话</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-29ac93c627360375.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图15.png"></p>
<p>4). 更新数据<br>I. user.xml添加配置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;	</span><br><span class="line">	&lt;!-- 修改用户信息 --&gt;</span><br><span class="line">	&lt;update id=&quot;updateUser&quot; parameterType=&quot;com.mazaiting.po.User&quot;&gt;</span><br><span class="line">		update user set username = #&#123;username&#125; where id = #&#123;id&#125;</span><br><span class="line">	&lt;/update&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 测试代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">public class MybatisTest &#123;</span><br><span class="line">	private SqlSessionFactory factory;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() throws IOException &#123;</span><br><span class="line">		// 1. 创建SqlSessionFactoryBuilder对象</span><br><span class="line">		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();</span><br><span class="line">		// 2. 加载配置文件</span><br><span class="line">		InputStream inputStream = Resources.getResourceAsStream(&quot;SqlMapConfig.xml&quot;);</span><br><span class="line">		// 3. 创建SqlSessionFactory对象</span><br><span class="line">		factory = builder.build(inputStream);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	public void testUpdateUser()&#123;</span><br><span class="line">		// 创建会话</span><br><span class="line">		SqlSession session = factory.openSession();</span><br><span class="line">		User user = new User();</span><br><span class="line">		user.setId(10);</span><br><span class="line">		user.setUsername(&quot;张某某&quot;);</span><br><span class="line">		// 更新数据</span><br><span class="line">		session.update(&quot;updateUser&quot;, user);</span><br><span class="line">		// 提交事务</span><br><span class="line">		session.commit();</span><br><span class="line">		// 关闭会话</span><br><span class="line">		session.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>III. 打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-8b871b1815247e17.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图16.png"></p>
<p>####5. Mybatis与Hibernate不同</p>
<ul>
<li>MyBatis学习成本低，入门门槛低。MyBatis需要程序员自己写sql，对sql修改和优化就比较灵活。MyBatis是不完全的ORM框架，MyBatis需要程序员编写sql，但是MyBatis也存在映射（输入映射、输出映射）适用场景：需求变化较快的项目开发，比如互联网项目、电商。</li>
<li>Hibernate学习成本高，入门门槛高，Hibernate是ORM框架，不需要程序员编写sql，自动根据对象映射生成sql。适用场景：需求固定的中小型项目，如OA系统、ERP系统。</li>
</ul>
<p>###<a href="https://download.csdn.net/download/mazaiting/10352107" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-Mybatis-Mapper使用/" rel="next" title="JavaEE-Mybatis-Mapper使用">
                <i class="fa fa-chevron-left"></i> JavaEE-Mybatis-Mapper使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring+Mybatis整合/" rel="prev" title="JavaEE-Spring+Mybatis整合">
                JavaEE-Spring+Mybatis整合 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
